﻿var CustomerValidationClientSideHide = false;
var TopScrollPossition = 0;
var IsFromOperationRoom = false;
var LinkCustomerID = 0;
var CurrentTab = 1;
var CurrentTabElement = null;
var PageNumber = 1;
var IsSearchView = false;
var ScrollPosition = 0;
var PaymentstrID = 0;
var SelectedCountryID = null;
var PhoneNumber1 = null;
var PhoneNumber2 = null;
var FaxNumber = null;
var GridPhone = [];
var GridFax = [];
var Phone = null;
var Fax = null;
var CustomerAutoComElem = null;
var CustomerAutoComElemVal = null;
var CustomerTimerId = null;
$(document).ready(function () {
    var path = window.location.pathname;
    if (path.indexOf("ManageCustomers") != -1) {
        IsFromOperationRoom = false;
        $.validator.addMethod("ManageCustomerRequireds", $.validator.methods.required, Messages["ManageCustomerRequireds"]);
        $.validator.addMethod("ManageCustomerDate", $.validator.methods.datePicker, Messages["ManageCustomerDate"]);
        $.validator.addMethod("ManageCustomerEmail", $.validator.methods.email, Messages["ManageCustomerEmail"]);
        $.validator.addMethod("ManageCustomerMaxLength15", $.validator.methods.maxlength, Messages["ManageCustomerMaxLength15"]);
        $.validator.addMethod("ManageCustomerMaxLength20", $.validator.methods.maxlength, Messages["ManageCustomerMaxLength20"]);
        $.validator.addMethod("ManageCustomerMaxLength30", $.validator.methods.maxlength, Messages["ManageCustomerMaxLength30"]);
        $.validator.addMethod("ManageCustomerMaxLength50", $.validator.methods.maxlength, Messages["ManageCustomerMaxLength50"]);
        $.validator.addMethod("ManageCustomerMaxLength100", $.validator.methods.maxlength, Messages["ManageCustomerMaxLength100"]);
        $.validator.addMethod("ManageCustomerMaxLength200", $.validator.methods.maxlength, Messages["ManageCustomerMaxLength200"]);
        $.validator.addMethod("ManageCustomerMaxLength250", $.validator.methods.maxlength, Messages["ManageCustomerMaxLength250"]);
        $.validator.addClassRules({
            Required: {
                ManageCustomerRequireds: true,
            },
            Email: {
                ManageCustomerEmail: true,
            },
            Date: {
                ManageCustomerDate: true,
            },
            MaxLength250: {
                ManageCustomerMaxLength250: 250,
            },
            MaxLength200: {
                ManageCustomerMaxLength200: 200,
            },
            MaxLength100: {
                ManageCustomerMaxLength100: 100,
            },
            MaxLength50: {
                ManageCustomerMaxLength50: 50,
            },
            MaxLength30: {
                ManageCustomerMaxLength30: 30,
            },
            MaxLength20: {
                ManageCustomerMaxLength20: 20,
            },
            MaxLength15: {
                ManageCustomerMaxLength15: 15,
            },
        });

        $('#LoadCustomerDetailsForm').validate();
        $('#LoadCustomerPaymentGroupsForm').validate();
        $('#LoadCustomerAddPaymentGroupsForm').validate();
        $('#LoadCustomerPaymentsForm').validate();
        $('#LoadCustomerAddPaymentsForm').validate();
        if (UrlParam("CustomerID") != null) {
            IsFromOperationRoom = true;
            var param = UrlParam("CustomerID");
            LinkCustomerID = param;
            LoadCustomerByID(param, true);
        }
        else
        {
            LoadCustomerGrid();
        }
        $(".Tab").click(function (event) {
            
            if ($(this).hasClass("active"))
            {
                return false;
            }
            if ($(this).hasClass("Tab"))
            {
                CurrentTabElement = this;
            }
            if (CurrentTab == 2 || CurrentTab == 3 || CurrentTab == 4 || (CurrentTab == 1 && !($('#CustomerDetailsSaveBtn').hasClass('BackColorRed'))) || (CurrentTab == 5 && !($('#CustomerPaymentsSaveBtn').hasClass('BackColorRed')) && !($('#CustomerPaymentGroupsSaveBtn').hasClass('BackColorRed')) && !($('#AddCustomerPaymentGroupsBtn').hasClass('BackColorRed')) && !($('#AddCustomerPaymentsBtn').hasClass('BackColorRed')))) {
                switch (CurrentTab) {
                    case 1:
                        {
                            $("#CustomerGeneral").removeClass("active");
                            $("#tabCustomerGeneral").removeClass("active in");
                            CustomerValidationClientSideHide = false;
                        }
                        break;
                    case 2:
                        {
                            $("#CustomerGroups").removeClass("active");
                            $("#tabCustomerGroups").removeClass("active in");
                            CustomerValidationClientSideHide = false;
                        }
                        break;
                    case 3:
                        {
                            $("#CustomerQuotations").removeClass("active");
                            $("#tabCustomerQuotations").removeClass("active in");
                            CustomerValidationClientSideHide = false;
                        }
                        break;
                    case 4:
                        {
                            $("#CustomerInvoices").removeClass("active");
                            $("#tabCustomerInvoices").removeClass("active in");
                            CustomerValidationClientSideHide = false;
                        }
                        break;
                    case 5:
                        {
                            $("#CustomerPayments").removeClass("active");
                            $("#tabCustomerPayments").removeClass("active in");
                            CustomerValidationClientSideHide = false;
                        }
                        break;
                    default:
                        break;
                }
                switch ($(CurrentTabElement).attr("id")) {
                    case "CustomerGeneral":
                        {
                            CurrentTab = 1;
                            $("#CustomerGeneral").addClass("active");
                            $("#tabCustomerGeneral").addClass("active in");
                            CustomerValidationClientSideHide = false;
                        }
                        break;
                    case "CustomerGroups":
                        {
                            CurrentTab = 2;
                            $("#CustomerGroups").addClass("active");
                            $("#tabCustomerGroups").addClass("active in");
                            CustomerValidationClientSideHide = false;
                        }
                        break;
                    case "CustomerQuotations":
                        {
                            CurrentTab = 3;
                            $("#CustomerQuotations").addClass("active");
                            $("#tabCustomerQuotations").addClass("active in");
                            CustomerValidationClientSideHide = false;
                        }
                        break;
                    case "CustomerInvoices":
                        {
                            CurrentTab = 4;
                            $("#CustomerInvoices").addClass("active");
                            $("#tabCustomerInvoices").addClass("active in");
                            CustomerValidationClientSideHide = false;
                        }
                        break;
                    case "CustomerPayments":
                        {
                            CurrentTab = 5;
                            $("#CustomerPayments").addClass("active");
                            $("#tabCustomerPayments").addClass("active in");
                            CustomerValidationClientSideHide = false;
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
            event.preventDefault();
            event.stopImmediatePropagation();
            if ($('#CustomerDetailsSaveBtn').hasClass('BackColorRed') && CurrentTab == 1) {
                jConfirm(Messages["ChangeTab"], Messages["ChangeTabTitle"], function (retVal) {
                    if (retVal != true) {
                        event.stopImmediatePropagation();
                        event.preventDefault();
                    }
                    else {
                        $("#CustomerGeneral").removeClass("active");
                        $("#tabCustomerGeneral").removeClass("active in");
                        switch ($(CurrentTabElement).attr("id")) {
                            case "CustomerGroups":
                                {
                                    CurrentTab = 2;
                                    $("#CustomerGroups").addClass("active");
                                    $("#tabCustomerGroups").addClass("active in");
                                    CustomerValidationClientSideHide = false;
                                }
                                break;
                            case "CustomerQuotations":
                                {
                                    CurrentTab = 3;
                                    $("#CustomerQuotations").addClass("active");
                                    $("#tabCustomerQuotations").addClass("active in");
                                    CustomerValidationClientSideHide = false;
                                }
                                break;
                            case "CustomerInvoices":
                                {
                                    CurrentTab = 4;
                                    $("#CustomerInvoices").addClass("active");
                                    $("#tabCustomerInvoices").addClass("active in");
                                    CustomerValidationClientSideHide = false;
                                }
                                break;
                            case "CustomerPayments":
                                {
                                    CurrentTab = 5;
                                    $("#CustomerPayments").addClass("active");
                                    $("#tabCustomerPayments").addClass("active in");
                                    CustomerValidationClientSideHide = false;
                                }
                                break;
                            default:
                                break;
                        }
                    }
                });
            }
            else {
                jConfirm(Messages["ChangeTab"], Messages["ChangeTabTitle"], function (retVal) {
                    if (retVal != true) {
                        event.stopImmediatePropagation();
                        event.preventDefault();
                    }
                    else {
                        $("#CustomerPayments").removeClass("active");
                        $("#tabCustomerPayments").removeClass("active in");
                        switch ($(CurrentTabElement).attr("id")) {
                            case "CustomerGeneral":
                                {
                                    CurrentTab = 1;
                                    $("#CustomerGeneral").addClass("active");
                                    $("#tabCustomerGeneral").addClass("active in");
                                    CustomerValidationClientSideHide = false;
                                }
                                break;
                            case "CustomerGroups":
                                {
                                    CurrentTab = 2;
                                    $("#CustomerGroups").addClass("active");
                                    $("#tabCustomerGroups").addClass("active in");
                                    CustomerValidationClientSideHide = false;
                                }
                                break;
                            case "CustomerQuotations":
                                {
                                    CurrentTab = 3;
                                    $("#CustomerQuotations").addClass("active");
                                    $("#tabCustomerQuotations").addClass("active in");
                                    CustomerValidationClientSideHide = false;
                                }
                                break;
                            case "CustomerInvoices":
                                {
                                    CurrentTab = 4;
                                    $("#CustomerInvoices").addClass("active");
                                    $("#tabCustomerInvoices").addClass("active in");
                                    CustomerValidationClientSideHide = false;
                                }
                                break;
                            default:
                                break;
                        }
                    }
                });
            }
        });
    }
});
$(document).on('change', '.CustomerDetailsElementChange', function () {
    if (!$('#CustomerDetailsSaveBtn').hasClass("disabled")) {
        $('#CustomerDetailsSaveBtn').addClass('BackColorRed');
    }
}); 
$(document).on('change', '.CustomerPaymentsChange', function () {
    if (!$('#CustomerPaymentsSaveBtn').hasClass("disabled")) {
        $('#CustomerPaymentsSaveBtn').addClass('BackColorRed');
    }
});
$(document).on('change', '.CustomerPaymentGroupsElementChange', function () {
    if (!$('#CustomerPaymentGroupsSaveBtn').hasClass("disabled")) {
        $('#CustomerPaymentGroupsSaveBtn').addClass('BackColorRed');
    }
});
$(document).on('change', '.AddCustomerPaymentGroupsElementChange', function () {
    if (!$('#AddCustomerPaymentGroupsBtn').hasClass("disabled")) {
        $('#AddCustomerPaymentGroupsBtn').addClass('BackColorRed');
    }
});
$(document).on('change', '.AddCustomerPaymentsElementChange', function () {
    if (!$('#AddCustomerPaymentsBtn').hasClass("disabled")) {
        $('#AddCustomerPaymentsBtn').addClass('BackColorRed');
    }
});
$(document).on('change', '.ChangedCustomerGridElements', function () {
    $('#CustomerGridSaveBtn').addClass('BackColorRed');
});
function GoToQuotation(QuotaID)
{
    if ($('#CustomerDetailsSaveBtn').hasClass('BackColorRed') || $('#CustomerPaymentsSaveBtn').hasClass('BackColorRed') || $('#CustomerPaymentGroupsSaveBtn').hasClass('BackColorRed') || $('#AddCustomerPaymentGroupsBtn').hasClass('BackColorRed') || $('#AddCustomerPaymentsBtn').hasClass('BackColorRed')) {
        jConfirm(Messages["ChangeTab"], Messages["ChangeTabTitle"], function (retVal) {
            if (retVal == true) {
                window.open('../Quotation/Quotation?QuotaId=' + QuotaID, ' _blank')
            }
        });
    }
    else
        window.open('../Quotation/Quotation?QuotaId=' + QuotaID, ' _blank')
}

function ShowCustomer(CustomerID)
{
    if (CustomerID == 0)
        AddCustomer(CustomerID);
    else
    {
        CurrentTab = 1;
        $("#CustomerGeneral").addClass("active");
        $("#tabCustomerGeneral").addClass("active in");
        ShowCustomerDetails(CustomerID);
        ShowCustomerGroups(CustomerID);
        ShowCustomerQuotations(CustomerID);
        ShowCustomerPayments(CustomerID);
    }
}
function ShowCustomerGroups(CustomerID) {
    $.ajax({
        url: urls["CustomerLoadCustomerGroups"],
        data: { 'CustomerID': CustomerID },
        type: 'GET',
        success: function (data) {
            $("#tabCustomerGroups").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
        }
    });
}
function ShowCustomerQuotations(CustomerID) {
    $.ajax({
        url: urls["CustomerLoadCustomerQuotations"],
        data: { 'CustomerID': CustomerID },
        type: 'GET',
        success: function (data) {
            $("#tabCustomerQuotations").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
        }
    });
}
function ShowCustomerDetails(CustomerID) {

    $.ajax({
        url: urls["CustomerLoadCustomerDetails"],
        data: { 'CustomerID': CustomerID },
        type: 'GET',
        success: function (data) {
            $("#tabCustomerGeneral").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            ShowCustomerDetailPopUp("CustomerDetailsDiv");
            InitCustomerDetailsDataCalendars();
        }
    });
}
function ShowCustomerPayments(CustomerID) {
    $.ajax({
        url: urls["CustomerLoadCustomerPayments"],
        data: { 'CustomerID': CustomerID, 'LineNo': $("#SelectedLineNo").val() },
        type: 'GET',
        success: function (data) {
            $("#tabCustomerPayments").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            ShowCustomerInvoices(CustomerID);
            ShowCustomerPaymentGroups(CustomerID, $("#SelectedLineNo").val());
            $("#PaymentsGridlochal").scrollTop(parseFloat(ScrollPosition));
            if ($("#" + PaymentstrID).length > 0) {
                $("#" + PaymentstrID).addClass('CustomerPaymentActiveColumn');
            }
            InitCustomerDetailsDataCalendars();
            BindCustomerPayTypeDrop();
        }
    });
}
function ShowCustomerPaymentGroups(CustomerID , LineNo ) {

    $.ajax({
        url: urls["CustomerLoadCustomerPaymentGroups"],
        data: { 'CustomerID': CustomerID, 'LineNo': LineNo},
        type: 'GET',
        success: function (data) {
            $("#CustomerPaymentDetDiv").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            $("#CustomerPaymentDetDiv").show();
            BindCustomerPayGroupDrop();
            $("#PaymentsGridlochal").scrollTop(parseFloat(ScrollPosition));
            $("#" + PaymentstrID).addClass('CustomerPaymentActiveColumn');
        }
    });
}
function ShowCustomerInvoices(CustomerID) {
    $.ajax({
        url: urls["CustomerLoadCustomerInvoices"],
        data: { 'CustomerID': CustomerID },
        type: 'GET',
        success: function (data) {
            $("#tabCustomerInvoices").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            $("#PaymentsGridlochal").scrollTop(parseFloat(ScrollPosition));
            $("#" + PaymentstrID).addClass('CustomerPaymentActiveColumn');
        }
    });
}
function AddCustomer(CustomerID) {
        $.ajax({
            url: urls["CustomerLoadCustomerDetails"],
            data: { 'CustomerID': CustomerID },
            type: 'GET',
            success: function (data) {
                $("#AddCustomerDiv").html(data);
            },
            error: function (xhr) {
                jAlert(xhr.statusText, "Error");
            },
            complete: function () {
                ShowCustomerDetailPopUp("AddCustomerDiv");
                InitCustomerDetailsDataCalendars();
            }
        });
}
$(document).on('click', '.GroupDetailClik', function () {
    var element = $(this).parent();
    var tdparent=null;
    if ($(element).is("tr"))
    {
        tdparent = element;
    }
    else
        tdparent = element.parent();
    var LineNo = $(tdparent).find("input.LineNoForFindGroup").val();
    $("#SelectedLineNo").val(LineNo);
    ScrollPosition = $("#PaymentsGridlochal").scrollTop();
    ShowCustomerPaymentGroups($("#CustomerID").val(), $("#SelectedLineNo").val());
    $("#" + PaymentstrID).removeClass('CustomerPaymentActiveColumn');
    PaymentstrID = parseInt(tdparent.attr('id'));
    $("#" + PaymentstrID).addClass('CustomerPaymentActiveColumn');
});
$(document).on('click', '#CustomerMoreBtn', function () {
    TopScrollPossition = $("#CusomerGridDetailDiv").scrollTop();
    PageNumber = PageNumber + 1;
    LoadCustomerGrid();
});
$(document).on('click', '#CustomerSearchBtn', function () {
    IsSearchView = true;
    LoadCustomerGrid();
});
$(document).on('change', '#SearchByGroupStatusDrop', function () {
    GroupIsSearchView = true;
    LoadCustomerGroupGrid();
});
$(document).on('click', '#CustomerGridSaveBtn', function () {
    var $form = $('#LoadCustomerGridForm');
    if ($form.valid()) {
        if ($form[0].length > 0) {
            $.ajax({
                url: $form.attr('action'),
                type: $form.attr('method'),
                data: $form.serialize(),
                beforeSend: function (xhr) {
                    xhr.overrideMimeType('text/plain; charset=x-user-defined');
                },
                success: function (data) {
                    if (data.indexOf("Error") != -1)
                        jAlert(data, "Error");
                },
                error: function (xhr) {
                    jAlert(xhr.statusText, "Error");
                },
                complete: function () {
                    $('#CustomerGridSaveBtn').removeClass('BackColorRed')
                    jAlert("Data SuccessFully Saved:", "Successful");
                    TopScrollPossition = $("#CusomerGridDetailDiv").scrollTop();
                    LoadCustomerGrid();
                }
            });
        }
        else
            jAlert("You have not data to save:", "Attention!");
    }
});
function ShowCustomerDetailPopUp(PopUpDiv) {
    $.colorbox({
        width: "1000px",
        height: "710px",
        inline: true,
        href: "#"+PopUpDiv,
        onComplete: function () {
            SelectedCountryID = $("#SelectedCountryID").val();
            GridPhone = [];
            $("#LoadCustomerDetailsForm .GridPhone").each(function (index, elem) {
                GridPhone.push($(elem).val());
            });
            GridFax = [];
            $("#LoadCustomerDetailsForm .GridFax").each(function (index, elem) {
                GridFax.push($(elem).val());
            });
            Phone = null;
            Fax = null;
            PhoneNumber1 = $("#PhoneNumber1").val();
            PhoneNumber2 = $("#PhoneNumber2").val();
            FaxNumber = $("#FaxNumber").val();
            FormattedPhoneNumbers(SelectedCountryID);
            $(".phone").mask("(###) ###-####");
            $(".phoneUSACAN").mask("+1 (###) ###-####");
            $(".phoneTR").mask("+90 (###) ###-####");
            $(".phoneFR").mask("+33 (#) ##-##-##-##");
            $(".phoneBEL").mask("+32 (#) ###-##-##");
            $(".phoneSWI").mask("+41 (##) ###-####");
            $(".phoneTS").mask("+216 (##) ###-###");
            $(".phoneALG").mask("+213 (##) ###-####");
            $(".phoneMA").mask("+212 (##) ###-####");
            $(".PostalCode").mask("#####-####");
            $("#" + PopUpDiv).show();
        },
        onClosed: function () {
            $("#" + PopUpDiv).hide();
        }
    });
}
function AddNewCustomerContactDetailsShow() {
    if ($('#CustomerDetailsSaveBtn').hasClass('BackColorRed')) {
        jConfirm('Are you sure you want to leave this page? You Have Not Saved Data', 'Warning!', function (retVal) {
            if (retVal == true) {

                $("#CustomerContactDetailsDiv").show();
                $("#CustomerSaveCloseAddNewCustomerContactDetailBtns").hide();
            }
        });
    }
    else {
        $("#CustomerContactDetailsDiv").show();
        $("#CustomerSaveCloseAddNewCustomerContactDetailBtns").hide();
    }
}
function AddNewCustomerContactDetailsClose() {
    $('#AddCustomerContactDetailBtn').removeClass('BackColorRed');
    $("#CustomerContactDetailsDiv").hide();
    $("#CustomerSaveCloseAddNewCustomerContactDetailBtns").show();
}
$(document).on('click', '#AddCustomerContactDetailBtn', function () {
    if ($('#CustomerDetailsSaveBtn').hasClass('BackColorRed')) {
        jConfirm('You Have Not Saved Data. If you add new data you lose unsaved data', 'Warning!', function (retVal) {
            if (retVal == true) {
                AddCustomerContactDetail();
            }
        });
    }
    else {
        AddCustomerContactDetail();
    }
});
function AddCustomerContactDetail() {
    if ($('#LoadAddCustomerContactDetailsForm').valid()) {
        var CustomerDetailsViewModel = {
            CustomerID: $("#CustomerID").val(),
            Name: $("#Name").val(),
            Title: $("#Title").val(),
            EMail: $("#EMail").val(),
            Phone: $("#Phone").val(),
            Fax: $("#Fax").val(),
        };

        var DTO = JSON.stringify(CustomerDetailsViewModel);
        $.ajax({
            url: urls["AddNewCustomerContactDetail"],
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: DTO,
            success: function (data) {
                $("#CustomerContactDetailsDiv").hide();
            },
            error: function (xhr) {
                jAlert(xhr.statusText, "Error");
            },
            complete: function () {
                $('#AddCustomerContactDetailBtn').removeClass('BackColorRed');
                jAlert("Data SuccessFully Saved:", "Successful");
                ShowCustomerDetails($("#CustomerID").val())
            }
        });
    }
}
function isValidGroup() {
    var isvalid = true
    var Codearr = [];
    $(".GroupCode").each(function (index, elem) {
        var Selectedindex = parseInt(elem.selectedIndex);
        var elemvalue = elem.options[elem.selectedIndex].value;
        Codearr.push(elemvalue);
    });
    for (var index = 0 ; index < Codearr.length ; ++index) {
        if (isvalid) {
            for (var index1 = index + 1 ; index1 < Codearr.length ; ++index1) {
                if (Codearr[index1] == Codearr[index]) {
                    isvalid = false;
                    break;
                }
            }
        }
        else
            break;
    }
    return isvalid;
}
function isEmptyGroup() {
    var isvalid = true
    var Codearr = [];
    $(".GroupCode").each(function (index, elem) {
        if (elem.selectedIndex == null || elem.selectedIndex == -1)
        {
            isvalid = false;
            return;
        }
    });
    return isvalid;
}
function isValidAddGroup(AddGroupSelectedindex) {
    var isvalid = true
    var Codearr = [];
    $(".GroupCode").each(function (index, elem) {
        var Selectedindex = parseInt(elem.selectedIndex);
        var elemvalue = elem.options[elem.selectedIndex].value;
        Codearr.push(elemvalue);
    });
    for (var index = 0 ; index < Codearr.length ; ++index) {
        if (AddGroupSelectedindex == Codearr[index]) {
            isvalid = false;
            break;
        }
    }
    return isvalid;
}
// Money textboxes format 
$(document).on('change', '.MoneyTxb', function () {
    var val = parseFloat(Math.round($(this).val() * 100) / 100).toFixed(2);
    $(this).val(val);
});
$(document).on('click', '#CustomerPaymentsSaveBtn', function () {
    var $form = $('#LoadCustomerPaymentsForm');
    if ($form.valid()) {
        if ($("#LoadCustomerPaymentsForm .LineNoForFindGroup").length > 0) {
            $.ajax({
                url: $form.attr('action'),
                type: $form.attr('method'),
                data: $form.serialize(),
                beforeSend: function (xhr) {
                    xhr.overrideMimeType('text/plain; charset=x-user-defined');
                },
                success: function (data) {
                    if (data.indexOf("Error") != -1)
                        jAlert(data, "Error");
                },
                error: function (xhr) {
                    jAlert(xhr.statusText, "Error")
                },
                complete: function () {
                    $('#CustomerPaymentsSaveBtn').removeClass('BackColorRed')
                    jAlert("Data SuccessFully Saved:", "Successful");
                    ShowCustomerPayments($("#CustomerID").val())
                    $("#PaymentsGridlochal").scrollTop(ScrollPosition);
                    $("#" + PaymentstrID).addClass('CustomerPaymentActiveColumn');
                }
            });
        }
        else
            jAlert("There are not any payment for save:", "Error!");
    }
});
$(document).on('click', '#CustomerPaymentGroupsSaveBtn', function () {
    var $form = $('#LoadCustomerPaymentGroupsForm');
    if (isEmptyGroup()) {
        if (isValidGroup()) {
            if ($form.valid()) {
                if ($("#LoadCustomerPaymentGroupsForm .GroupCode").length > 0) {
                    $.ajax({
                        url: $form.attr('action'),
                        type: $form.attr('method'),
                        data: $form.serialize(),
                        beforeSend: function (xhr) {
                            xhr.overrideMimeType('text/plain; charset=x-user-defined');
                        },
                        success: function (data) {
                            if (data.indexOf("Error") != -1)
                                jAlert(data, "Error");
                            else {
                                $("#tabCustomerPayments").html(data);
                            }
                        },
                        error: function (xhr) {
                            jAlert(xhr.statusText, "Error");
                        },
                        complete: function () {
                            $('#CustomerPaymentGroupsSaveBtn').removeClass('BackColorRed')
                            jAlert("Data SuccessFully Saved:", "Successful");
                            ShowCustomerPayments($("#CustomerID").val());
                        }
                    });
                }
                else
                    jAlert("There are not any group for save:", "Error!");
            }
        }
        else
            jAlert("Payment Group Must Be Different:", "Error!");
    }
    else
        jAlert("There are empty group in this payment:", "Error!");
});
$(document).on('click', '#CustomerDetailsSaveBtn', function () {
    var $form = $('#LoadCustomerDetailsForm');
    if ($form.valid()) {
        CustomerValidationClientSideHide = false;
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: $form.serialize(),
            beforeSend: function (xhr) {
                xhr.overrideMimeType('text/plain; charset=x-user-defined');
            },
            success: function (data) {
                if (data.indexOf("Error") != -1)
                    jAlert(data, "Error");
            },
            error: function (xhr) {
                jAlert(xhr.statusText, "Error");
            },
            complete: function () {
                $('#CustomerDetailsSaveBtn').removeClass('BackColorRed')
                if ($("#CustomerID").val() == 0) {
                    jAlert("Data SuccessFully Saved:", "Successful");
                    $('#cboxClose').click();
                    if (IsFromOperationRoom) {
                        LoadCustomerByID(LinkCustomerID, false);
                    }
                    else {
                        LoadCustomerGrid();
                    }
                    ShowCustomer(-1)
                }
                else {
                    jAlert("Data SuccessFully Saved:", "Successful");
                    ShowCustomerDetails($("#CustomerID").val())
                }
            }
        });
    }
    else
        CustomerValidationClientSideHide = true;
});
function InitCustomerDetailsDataCalendars() {
   
    $(".CustomerDeteilsDataCalendar").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1,
        dateFormat: 'dd/M/yy',
        beforeShow: function (input) {
            $(input).css({
                "position": "relative",
                "z-index": 999999
            });
        }
    });
}
function LoadCustomerGrid()
{
    var ManageCustomersGridViewModel = {
        OrganizationNameText: $("#OrganizationNameText").val(),
        CustomerCodeText: $("#CustomerCodeText").val(),
        CitySearchText: $("#CitySearchText").val(),
        PageNum: parseInt(PageNumber),
        IsActiveSearch: $("#IsActiveSearch").val(),
        IsSearch: IsSearchView,
        TopScrollPossition: parseFloat(TopScrollPossition),
    };
    
    var DTO = JSON.stringify(ManageCustomersGridViewModel);
    $.ajax({
        url: urls["CustomerLoadCustomersGrid"],
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: DTO,
        success: function (data) {
            $("#ManageCustomerGrid").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            if ($("#TopScrollPossition").val() != "") {
                $("#CusomerGridDetailDiv").scrollTop(parseFloat($("#TopScrollPossition").val()));
            }
        }
    });
}
function LoadCustomerByID(CustomerID, IsOpenCustomerDetails) {
    $.ajax({
        url: urls["CustomerLoadCustomer"],
        data: { 'CustomerID': CustomerID },
        type: 'Post',
        success: function (data) {
            $("#ManageCustomerGrid").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {
            if (IsOpenCustomerDetails) {
                ShowCustomer(CustomerID);
            }
        }
    });
}

function LoadCustomerGroupGrid() {
    var MangeCustomerGroupsGridViewModel = {
        SelectedGroupStatus: $("#SearchByGroupStatusDrop").val(),
        CustomerID:$("#SearchCustomerID").val(),
    };

    var DTO = JSON.stringify(MangeCustomerGroupsGridViewModel);
    $.ajax({
        url: urls["CustomerLoadCustomerSearchedGroups"],
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: DTO,
        success: function (data) {
            $("#tabCustomerGroups").html(data);
        },
        error: function (xhr) {
            jAlert(xhr.statusText, "Error");
        },
        complete: function () {

        }
    });
}
function BindCustomerPayTypeDrop() {
    $(".PaymentDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
    });
}
$(document).on('change', '.PaymentDrop', function () {
    $(".PaymentDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
    });
});
function BindCustomerPayGroupDrop() {
    $(".PaymentGroupDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
    });
}
$(document).on('change', '.PaymentGroupDrop', function () {
    $(".PaymentGroupDrop").each(function (index, elem) {
        $(elem).next().prop("selectedIndex", $(elem).prop("selectedIndex"));
    });
});
function AddNewPaymentShow() {
    if ($('#CustomerPaymentsSaveBtn').hasClass('BackColorRed')) {
        jConfirm('Are you sure you want to leave this page? You Have Not Saved Data', 'Warning!', function (retVal) {
            if (retVal == true) {
                $("#AddPaymentDiv").show();
                $("#PaymentSaveCloseAddNewPaymentBtns").hide();
            }
        });
    }
    else {
        $("#AddPaymentDiv").show();
        $("#PaymentSaveCloseAddNewPaymentBtns").hide();
    }
}
function AddNewPaymentsClose() {
    $('#AddCustomerPaymentsBtn').removeClass('BackColorRed')
    $("#AddPaymentDiv").hide();
    $("#PaymentSaveCloseAddNewPaymentBtns").show();
}
function AddNewPaymentGroupShow() {
    if ($('#CustomerPaymentGroupsSaveBtn').hasClass('BackColorRed')) {
        jConfirm('Are you sure you want to leave this page? You Have Not Saved Data', 'Warning!', function (retVal) {
            if (retVal == true) {
                $("#AddPaymentGroupDiv").show();
                $("#PaymentSaveCloseAddNewPaymentGroupBtns").hide();
            }
        });
    }
    else {
        $("#AddPaymentGroupDiv").show();
        $("#PaymentSaveCloseAddNewPaymentGroupBtns").hide();
    }
};
function AddNewPaymentGroupsClose() {
    $('#AddCustomerPaymentGroupsBtn').removeClass('BackColorRed')
    $("#AddPaymentGroupDiv").hide();
    $("#PaymentSaveCloseAddNewPaymentGroupBtns").show();
}
$(document).on('click', '#AddCustomerPaymentsBtn', function () {
    if ($('#CustomerPaymentsSaveBtn').hasClass('BackColorRed')) {
        jConfirm('You Have Not Saved Payments Data. If you add new payment you lose unsaved data', 'Warning!', function (retVal) {
            if (retVal == true) {
                AddCustomerPayment();
            }
        });
    }
    else {
        AddCustomerPayment();
    }
});
function AddCustomerPayment() {
    ScrollPosition = 6000;
    PaymentstrID = parseInt($("#RowsCount").val());

    if ($('#LoadCustomerAddPaymentsForm').valid()) {
        var ManageCustomerPaymentsGridViewModel = {
            AddPayTypeIDSelected: $(".CustomerPaymentAddPayTypeID").val(),
            CustomerID: $("#CustomerID").val(),
            PaymentDate: $(".CustomerPaymentDate").val(),
            RefundF: $(".CustomerPaymentRefundF").prop('checked'),
            Description: $(".CustomerPaymentDescription").val(),
            Debit: $(".CustomerPaymentDebit").val(),
            Credit: $(".CustomerPaymentCredit").val(),
        };

        var DTO = JSON.stringify(ManageCustomerPaymentsGridViewModel);
        $.ajax({
            url: urls["CustomerAddNewCustomerPayment"],
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: DTO,
            success: function (data) {
                AddNewPaymentsClose();
                $("#tabCustomerPayments").html(data);
            },
            error: function (xhr) {
                jAlert(xhr.statusText, "Error");
            },
            complete: function () {
                $('#AddCustomerPaymentsBtn').removeClass('BackColorRed')
                jAlert("Data SuccessFully Saved:", "Successful");
                ShowCustomerPayments($("#CustomerID").val());
                $("#PaymentsGridlochal").scrollTop(ScrollPosition);
                $("#PaymentsGridlochal").removeClass('CustomerPaymentActiveColumn');
                $("#" + PaymentstrID).addClass('CustomerPaymentActiveColumn');
            }
        });
    }
}
function ShowOperationInvoice(GrouCode, IsPushed)
{
    if(IsPushed)
    {
        window.open('../Operation/Operation?Roomtab=Y&GroupCode=' + GrouCode, '_blank');
    }
    else
    {
        jAlert("This group is not created yet:", "Warning!");
    }
}
$(document).on('click', '#AddCustomerPaymentGroupsBtn', function () {
    if ($('#CustomerPaymentsSaveBtn').hasClass('BackColorRed') || $('#CustomerPaymentGroupsSaveBtn').hasClass('BackColorRed')) {
        jConfirm(Messages["ClosePopUp"], Messages["ClosePopUpTitle"], function (retVal) {
            if (retVal == true) {
                AddCustomerPaymentGroup();
            }
        });
    }
    else {
        AddCustomerPaymentGroup();
    }
});
function AddCustomerPaymentGroup() {
    if ($(".CustomerPaymentAddGroupID").val() == null) {
        jAlert("You have not any group for this customer:", "Error!");
    }
    else {
        if (isValidAddGroup($(".CustomerPaymentAddGroupID").val())) {
            if ($('#LoadCustomerAddPaymentGroupsForm').valid()) {
                if ($("#LoadCustomerPaymentsForm .LineNoForFindGroup").length > 0) {
                    var ManageCustomerPaymentGroupsGridViewModel = {
                        AddGroupID: $(".CustomerPaymentAddGroupID").val(),
                        Received: $(".CustomerDepositeReceived").val(),
                        Refunded: $(".CustomerDepositeRefunded").val(),
                        CustomerID: $("#CustomerID").val(),
                        LineNo: $("#SelectedLineNo").val(),
                    };

                    var DTO = JSON.stringify(ManageCustomerPaymentGroupsGridViewModel);
                    $.ajax({
                        url: urls["CustomerAddNewCustomerPaymentGroups"],
                        type: 'POST',
                        contentType: 'application/json; charset=utf-8',
                        data: DTO,
                        success: function (data) {
                            AddNewPaymentsClose();
                            $("#tabCustomerPayments").html(data);
                        },
                        error: function (xhr) {
                            jAlert(xhr.statusText, "Error");
                        },
                        complete: function () {
                            $('#AddCustomerPaymentGroupsBtn').removeClass('BackColorRed')
                            jAlert("Data SuccessFully Saved:", "Successful");
                            ShowCustomerPayments($("#CustomerID").val());
                            $("#PaymentsGridlochal").scrollTop(ScrollPosition);
                            $("#" + PaymentstrID).addClass('CustomerPaymentActiveColumn');
                        }
                    });
                }
                else
                    jAlert("You have not any payment:", "Error!");
            }
        }
        else
            jAlert("Payment Group Must Be Different:", "Error!");
    }
}
$(document).on('change', '.CountryDrop', function () {
    FormattedPhoneNumbers($(this).val());
    if ($(this).val() === "") {
        $("#StateDiv").hide();
        $("#CityDiv").hide();
        $("#StateDivChange").show();
        $("#CityDivChange").show();
    }
    if ($(this).val() === '1') {
        $("#CityDiv").hide();
        $("#CityDivChange").show();
    }
    if ($(this).val() === '1') {
        $.ajax({
            url: urls["CustomerGetStateByCountryID"],
            data: { CountryID: parseInt($(this).val()) },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Select</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("Select.StateDrop").html(markup);
            },
            error: function (reponse) {
                jAlert(reponse, "Error");
            },
            complete: function () {
                $("#StateDiv").show();
                $("#StateDivChange").hide();
            }
        });
    }
    else if ($(this).val() != "") {
        $.ajax({
            url: urls["CustomerGetCityByCountryID"],
            data: { CountryID: parseInt($(this).val()), StateID: '0' },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Select</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("Select.CityDrop").html(markup);
            },
            error: function (reponse) {
                jAlert(reponse, "Error");
            },
            complete: function () {
                $("#StateDiv").hide();
                $("#StateDivChange").show();
                $("#CityDiv").show();
                $("#CityDivChange").hide();
            }
        });
    }
});
$(document).on('change', '.StateDrop', function () {
    var StateID = $(this).val();
    $.ajax({
        url: urls["CustomerGetCityByCountryID"],
        data: { CountryID: 0, StateID: StateID },
        cache: false,
        type: "POST",
        success: function (data) {
            var markup = "<option value='0'>Select</option>";
            for (var x = 0; x < data.length; x++) {
                markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
            }
            $("Select.CityDrop").html(markup);
        },
        error: function (reponse) {
            jAlert(reponse, "Error");
        },
        complete: function () {
            if (StateID === "" || StateID === "0") {
                $("#CityDiv").hide();
                $("#CityDivChange").show();
            }
            else {
                $("#CityDiv").show();
                $("#CityDivChange").hide();
            }
        }
    });
});
$(document).on('change', '.GridPhone', function () {
    GridPhone = [];
    $("#LoadCustomerDetailsForm .GridPhone").each(function (index, elem) {
        GridPhone.push($(elem).val());
    });
});
$(document).on('change', '.GridFax', function () {
    GridFax = [];
    $("#LoadCustomerDetailsForm .GridFax").each(function (index, elem) {
        GridFax.push($(elem).val());
    });
});
$(document).on('change', '#Phone', function () {
    Phone = $(this).val();
});
$(document).on('change', '#Fax', function () {
    Fax = $(this).val();
});
$(document).on('change', '#PhoneNumber1', function () {
    PhoneNumber1 = $(this).val();
});
$(document).on('change', '#PhoneNumber2', function () {
    PhoneNumber2 = $(this).val();
});
$(document).on('change', '#FaxNumber', function () {
    FaxNumber = $(this).val();
});
$(document).on('change', '#PhoneNumberUnformatted', function () {
    if ($("#PhoneNumberUnformatted").prop('checked') == true)
    {
        $(".phone").unmask();
        $(".phoneUSACAN").unmask();
        $(".phoneTR").unmask();
        $(".phoneFR").unmask();
        $(".phoneBEL").unmask();
        $(".phoneSWI").unmask();
        $(".phoneTS").unmask();
        $(".phoneALG").unmask();
        $(".phoneMA").unmask();

        $("#LoadCustomerDetailsForm .GridPhone").each(function (index, elem) {
            $(elem).addClass("number");
        });
        $("#LoadCustomerDetailsForm .GridFax").each(function (index, elem) {
            $(elem).addClass("number");
        });
        $("#Phone").addClass("number");
        $("#Fax").addClass("number");
        $("#PhoneNumber1").addClass("number");
        $("#PhoneNumber2").addClass("number");
        $("#FaxNumber").addClass("number");
        $(".number").maskMoney({ prefix: '', allowNegative: false, thousands: '', decimal: '', affixesStay: false, precision: 0 });

        $("#LoadCustomerDetailsForm .GridPhone").each(function (index, elem) {
            $(elem).val(GridPhone[index]);
        });
        $("#LoadCustomerDetailsForm .GridFax").each(function (index, elem) {
            $(elem).val(GridFax[index]);
        });
        $("#Phone").val(Phone);
        $("#Fax").val(Fax);
        $("#PhoneNumber1").val(PhoneNumber1);
        $("#PhoneNumber2").val(PhoneNumber2);
        $("#FaxNumber").val(FaxNumber);
    }
    else {
        $(".number").unmask();
        $("#LoadCustomerDetailsForm .GridPhone").each(function (index, elem) {
            $(elem).removeClass("number");
        });
        $("#LoadCustomerDetailsForm .GridFax").each(function (index, elem) {
            $(elem).removeClass("number");
        });
        $("#Phone").removeClass("number");
        $("#Fax").removeClass("number");
        $("#PhoneNumber1").removeClass("number");
        $("#PhoneNumber2").removeClass("number");
        $("#FaxNumber").removeClass("number");
        FormattedPhoneNumbers($("#SelectedCountryID").val())
    }
});
function FormattedPhoneNumbers(CountryID) {
    if ($("#PhoneNumberUnformatted").prop('checked') != true) {
        $("#LoadCustomerDetailsForm .GridPhone").each(function (index, elem) {
            $(elem).val(GridPhone[index]);
        });
        $("#LoadCustomerDetailsForm .GridFax").each(function (index, elem) {
            $(elem).val(GridFax[index]);
        });
        $("#Phone").val(Phone);
        $("#Fax").val(Fax);
        $("#PhoneNumber1").val(PhoneNumber1);
        $("#PhoneNumber2").val(PhoneNumber2);
        $("#FaxNumber").val(FaxNumber);

        switch (CountryID) {
            case '1': case '7':
                {
                    if (SelectedCountryID == '1' || SelectedCountryID == '7') {
                        $("#LoadCustomerDetailsForm .GridPhone").each(function (index, elem) {
                            $(elem).val(GridPhone[index]);
                        });
                        $("#LoadCustomerDetailsForm .GridFax").each(function (index, elem) {
                            $(elem).val(GridFax[index]);
                        });
                        $("#Phone").val(Phone);
                        $("#Fax").val(Fax);
                        $("#PhoneNumber1").val(PhoneNumber1);
                        $("#PhoneNumber2").val(PhoneNumber2);
                        $("#FaxNumber").val(FaxNumber);
                    }
                    $("#LoadCustomerDetailsForm .GridPhone").each(function (index, elem) {
                        $(elem).removeAttr('class');
                        $(elem).addClass('CustomerDetailsElementChange table_inputs_180 table_inputs_WithoutBox GridPhone ElementsForValidation MaxLength20 phoneUSACAN');
                    });
                    $("#LoadCustomerDetailsForm .GridFax").each(function (index, elem) {
                        $(elem).removeAttr('class');
                        $(elem).addClass('CustomerDetailsElementChange table_inputs_180 table_inputs_WithoutBox GridFax ElementsForValidation MaxLength20 phoneUSACAN');
                    });
                    $("#Phone").removeAttr('class');
                    $("#Phone").addClass('AddCustomerContactDetailsElementChange table_inputs_180 table_inputs_WithoutBox ElementsForValidation MaxLength20 phoneUSACAN');
                    $("#Fax").removeAttr('class');
                    $("#Fax").addClass('AddCustomerContactDetailsElementChange table_inputs_180 table_inputs_WithoutBox ElementsForValidation MaxLength20 phoneUSACAN');
                    $("#PhoneNumber1").removeAttr('class');
                    $("#PhoneNumber1").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneUSACAN');
                    $("#PhoneNumber2").removeAttr('class');
                    $("#PhoneNumber2").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneUSACAN');
                    $("#FaxNumber").removeAttr('class');
                    $("#FaxNumber").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneUSACAN');
                    $(".phoneUSACAN").mask("+1 (###) ###-####");
                };
                break;
            case '3':
                {
                    $("#LoadCustomerDetailsForm .GridPhone").each(function (index, elem) {
                        $(elem).removeAttr('class');
                        $(elem).addClass('CustomerDetailsElementChange table_inputs_180 table_inputs_WithoutBox GridPhone ElementsForValidation MaxLength20 phoneTR');
                    });
                    $("#LoadCustomerDetailsForm .GridFax").each(function (index, elem) {
                        $(elem).removeAttr('class');
                        $(elem).addClass('CustomerDetailsElementChange table_inputs_180 table_inputs_WithoutBox GridFax ElementsForValidation MaxLength20 phoneTR');
                    });
                    $("#Phone").removeAttr('class');
                    $("#Phone").addClass('AddCustomerContactDetailsElementChange table_inputs_180 table_inputs_WithoutBox ElementsForValidation MaxLength20 phoneTR');
                    $("#Fax").removeAttr('class');
                    $("#Fax").addClass('AddCustomerContactDetailsElementChange table_inputs_180 table_inputs_WithoutBox ElementsForValidation MaxLength20 phoneTR');
                    $("#PhoneNumber1").removeAttr('class');
                    $("#PhoneNumber1").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneTR');
                    $("#PhoneNumber2").removeAttr('class');
                    $("#PhoneNumber2").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneTR');
                    $("#FaxNumber").removeAttr('class');
                    $("#FaxNumber").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneTR');
                    $(".phoneTR").mask("+90 (###) ###-####");
                };
                break;
            case '5':
                {
                    $("#LoadCustomerDetailsForm .GridPhone").each(function (index, elem) {
                        $(elem).removeAttr('class');
                        $(elem).addClass('CustomerDetailsElementChange table_inputs_180 table_inputs_WithoutBox GridPhone ElementsForValidation MaxLength20 phoneFR');
                    });
                    $("#LoadCustomerDetailsForm .GridFax").each(function (index, elem) {
                        $(elem).removeAttr('class');
                        $(elem).addClass('CustomerDetailsElementChange table_inputs_180 table_inputs_WithoutBox GridFax ElementsForValidation MaxLength20 phoneFR');
                    });
                    $("#Phone").removeAttr('class');
                    $("#Phone").addClass('AddCustomerContactDetailsElementChange table_inputs_180 table_inputs_WithoutBox ElementsForValidation MaxLength20 phoneFR');
                    $("#Fax").removeAttr('class');
                    $("#Fax").addClass('AddCustomerContactDetailsElementChange table_inputs_180 table_inputs_WithoutBox ElementsForValidation MaxLength20 phoneFR');
                    $("#PhoneNumber1").removeAttr('class');
                    $("#PhoneNumber1").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneFR');
                    $("#PhoneNumber2").removeAttr('class');
                    $("#PhoneNumber2").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneFR');
                    $("#FaxNumber").removeAttr('class');
                    $("#FaxNumber").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneFR');
                    $(".phoneFR").mask("+33 (#) ##-##-##-##");
                };
                break
            case '8':
                {
                    $("#LoadCustomerDetailsForm .GridPhone").each(function (index, elem) {
                        $(elem).removeAttr('class');
                        $(elem).addClass('CustomerDetailsElementChange table_inputs_180 table_inputs_WithoutBox GridPhone ElementsForValidation MaxLength20 phoneBEL');
                    });
                    $("#LoadCustomerDetailsForm .GridFax").each(function (index, elem) {
                        $(elem).removeAttr('class');
                        $(elem).addClass('CustomerDetailsElementChange table_inputs_180 table_inputs_WithoutBox GridFax ElementsForValidation MaxLength20 phoneBEL');
                    });
                    $("#Phone").removeAttr('class');
                    $("#Phone").addClass('AddCustomerContactDetailsElementChange table_inputs_180 table_inputs_WithoutBox ElementsForValidation MaxLength20 phoneBEL');
                    $("#Fax").removeAttr('class');
                    $("#Fax").addClass('AddCustomerContactDetailsElementChange table_inputs_180 table_inputs_WithoutBox ElementsForValidation MaxLength20 phoneBEL');
                    $("#PhoneNumber1").removeAttr('class');
                    $("#PhoneNumber1").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneBEL');
                    $("#PhoneNumber2").removeAttr('class');
                    $("#PhoneNumber2").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneBEL');
                    $("#FaxNumber").removeAttr('class');
                    $("#FaxNumber").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneBEL');
                    $(".phoneBEL").mask("+32 (#) ###-##-##");
                };
                break
            case '11':
                {
                    $("#LoadCustomerDetailsForm .GridPhone").each(function (index, elem) {
                        $(elem).removeAttr('class');
                        $(elem).addClass('CustomerDetailsElementChange table_inputs_180 table_inputs_WithoutBox GridPhone ElementsForValidation MaxLength20 phoneSWI');
                    });
                    $("#LoadCustomerDetailsForm .GridFax").each(function (index, elem) {
                        $(elem).removeAttr('class');
                        $(elem).addClass('CustomerDetailsElementChange table_inputs_180 table_inputs_WithoutBox GridFax ElementsForValidation MaxLength20 phoneSWI');
                    });
                    $("#Phone").removeAttr('class');
                    $("#Phone").addClass('AddCustomerContactDetailsElementChange table_inputs_180 table_inputs_WithoutBox ElementsForValidation MaxLength20 phoneSWI');
                    $("#Fax").removeAttr('class');
                    $("#Fax").addClass('AddCustomerContactDetailsElementChange table_inputs_180 table_inputs_WithoutBox ElementsForValidation MaxLength20 phoneSWI');
                    $("#PhoneNumber1").removeAttr('class');
                    $("#PhoneNumber1").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneSWI');
                    $("#PhoneNumber2").removeAttr('class');
                    $("#PhoneNumber2").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneSWI');
                    $("#FaxNumber").removeAttr('class');
                    $("#FaxNumber").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneSWI');
                    $(".phoneSWI").mask("+41 (##) ###-####");
                };
                break
            case '12':
                {
                    $("#LoadCustomerDetailsForm .GridPhone").each(function (index, elem) {
                        $(elem).removeAttr('class');
                        $(elem).addClass('CustomerDetailsElementChange table_inputs_180 table_inputs_WithoutBox GridPhone ElementsForValidation MaxLength20 phoneTS');
                    });
                    $("#LoadCustomerDetailsForm .GridFax").each(function (index, elem) {
                        $(elem).removeAttr('class');
                        $(elem).addClass('CustomerDetailsElementChange table_inputs_180 table_inputs_WithoutBox GridFax ElementsForValidation MaxLength20 phoneTS');
                    });
                    $("#Phone").removeAttr('class');
                    $("#Phone").addClass('AddCustomerContactDetailsElementChange table_inputs_180 table_inputs_WithoutBox ElementsForValidation MaxLength20 phoneTS');
                    $("#Fax").removeAttr('class');
                    $("#Fax").addClass('AddCustomerContactDetailsElementChange table_inputs_180 table_inputs_WithoutBox ElementsForValidation MaxLength20 phoneTS');
                    $("#PhoneNumber1").removeAttr('class');
                    $("#PhoneNumber1").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneTS');
                    $("#PhoneNumber2").removeAttr('class');
                    $("#PhoneNumber2").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneTS');
                    $("#FaxNumber").removeAttr('class');
                    $("#FaxNumber").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneTS');
                    $(".phoneTS").mask("+216 (##) ###-###");
                };
                break
            case '24':
                {
                    $("#LoadCustomerDetailsForm .GridPhone").each(function (index, elem) {
                        $(elem).removeAttr('class');
                        $(elem).addClass('CustomerDetailsElementChange table_inputs_180 table_inputs_WithoutBox GridPhone ElementsForValidation MaxLength20 phoneALG');
                    });
                    $("#LoadCustomerDetailsForm .GridFax").each(function (index, elem) {
                        $(elem).removeAttr('class');
                        $(elem).addClass('CustomerDetailsElementChange table_inputs_180 table_inputs_WithoutBox GridFax ElementsForValidation MaxLength20 phoneALG');
                    });
                    $("#Phone").removeAttr('class');
                    $("#Phone").addClass('AddCustomerContactDetailsElementChange table_inputs_180 table_inputs_WithoutBox ElementsForValidation MaxLength20 phoneALG');
                    $("#Fax").removeAttr('class');
                    $("#Fax").addClass('AddCustomerContactDetailsElementChange table_inputs_180 table_inputs_WithoutBox ElementsForValidation MaxLength20 phoneALG');
                    $("#PhoneNumber1").removeAttr('class');
                    $("#PhoneNumber1").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneALG');
                    $("#PhoneNumber2").removeAttr('class');
                    $("#PhoneNumber2").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneALG');
                    $("#FaxNumber").removeAttr('class');
                    $("#FaxNumber").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneALG');
                    $(".phoneALG").mask("+213 (##) ###-####");
                };
                break
            case '26':
                {
                    $("#LoadCustomerDetailsForm .GridPhone").each(function (index, elem) {
                        $(elem).removeAttr('class');
                        $(elem).addClass('CustomerDetailsElementChange table_inputs_180 table_inputs_WithoutBox GridPhone ElementsForValidation MaxLength20 phoneMA');
                    });
                    $("#LoadCustomerDetailsForm .GridFax").each(function (index, elem) {
                        $(elem).removeAttr('class');
                        $(elem).addClass('CustomerDetailsElementChange table_inputs_180 table_inputs_WithoutBox GridFax ElementsForValidation MaxLength20 phoneMA');
                    });
                    $("#Phone").removeAttr('class');
                    $("#Phone").addClass('AddCustomerContactDetailsElementChange table_inputs_180 table_inputs_WithoutBox ElementsForValidation MaxLength20 phoneMA');
                    $("#Fax").removeAttr('class');
                    $("#Fax").addClass('AddCustomerContactDetailsElementChange table_inputs_180 table_inputs_WithoutBox ElementsForValidation MaxLength20 phoneMA');
                    $("#PhoneNumber1").removeAttr('class');
                    $("#PhoneNumber1").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneMA');
                    $("#PhoneNumber2").removeAttr('class');
                    $("#PhoneNumber2").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneMA');
                    $("#FaxNumber").removeAttr('class');
                    $("#FaxNumber").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phoneMA');
                    $(".phoneMA").mask("+212 (##) ###-####");
                };
                break
            default:
                {
                    $("#LoadCustomerDetailsForm .GridPhone").each(function (index, elem) {
                        $(elem).removeAttr('class');
                        $(elem).addClass('CustomerDetailsElementChange table_inputs_180 table_inputs_WithoutBox GridPhone ElementsForValidation MaxLength20 phone');
                    });
                    $("#LoadCustomerDetailsForm .GridFax").each(function (index, elem) {
                        $(elem).removeAttr('class');
                        $(elem).addClass('CustomerDetailsElementChange table_inputs_180 table_inputs_WithoutBox GridFax ElementsForValidation MaxLength20 phone');
                    });
                    $("#Phone").removeAttr('class');
                    $("#Phone").addClass('AddCustomerContactDetailsElementChange table_inputs_180 table_inputs_WithoutBox ElementsForValidation MaxLength20 phone');
                    $("#Fax").removeAttr('class');
                    $("#Fax").addClass('AddCustomerContactDetailsElementChange table_inputs_180 table_inputs_WithoutBox ElementsForValidation MaxLength20 phone');
                    $("#PhoneNumber1").removeAttr('class');
                    $("#PhoneNumber1").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phone');
                    $("#PhoneNumber2").removeAttr('class');
                    $("#PhoneNumber2").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phone');
                    $("#FaxNumber").removeAttr('class');
                    $("#FaxNumber").addClass('table_inputs_SmallPadding2 inpputgr form-control ElementsForValidation MaxLength20 CustomerDetailsElementChange phone');
                    $(".phone").mask("(###) ###-####");
                };
        }
    }
}


// text element complete text 
$(document).on('input', '.QuotaTxtComplete', function () {
    if (CustomerTimerId == null) {
        CustomerAutoComElem = $(this).attr('id');
        CustomerAutoComElemVal = $("#" + CustomerAutoComElem).val();
        CustomerTimerId = setInterval(function () {

            var keyword = $("#" + CustomerAutoComElem).val();
            if (keyword == CustomerAutoComElemVal) {
                var PropName = "";
                if (CustomerAutoComElem.indexOf("OrganizationNameText") != -1)
                    PropName = "OrganizationNameText";
                if (CustomerAutoComElem.indexOf("CustomerCodeText") != -1)
                    PropName = "CustomerCodeText";

                var position = $("#" + CustomerAutoComElem).offset();
                position.top = position.top + $("#" + CustomerAutoComElem).height() + 5;
                $.ajax({
                    url: urls["CustomerAutoComplete"],
                    data: { 'PropName': PropName, 'keyword': keyword },
                    type: 'POST',
                    success: function (data) {
                        $("#AutoCompleteDiv").html(data);
                        var width = $("#" + CustomerAutoComElem).css("width");
                        $("#AutoCompleteDiv").css("width", width);
                        $("#AutoCompleteDiv").show();
                        $("#AutoCompleteDiv").offset(position);
                    },
                    error: function (xhr) {
                        jAlert(xhr.statusText, "Error");
                    },
                    complete: function () {
                        clearInterval(CustomerTimerId);
                        CustomerTimerId = null;
                    }
                });
            }
            else
                CustomerAutoComElemVal = keyword;
        }, 600);
    }
});
$(document).on('click', '.QuotaAutoCompleteDivClose', function () {
    $(this).parent().parent().hide();
});
function htmlDecode(value) {
    return $('<div/>').html(value).text();
}
function AutoCompleteRowClick(key, val) {
    val = htmlDecode(val);
    $("#" + CustomerAutoComElem).val(val);
    if (CustomerAutoComElem.indexOf("OrganizationNameText") != -1)
        $("#" + CustomerAutoComElem).next().val(key);
    if (CustomerAutoComElem.indexOf("CustomerCodeText") != -1)
        $("#" + CustomerAutoComElem).next().val(key);
    $("#AutoCompleteDiv").hide();
}

var originalClose = $.colorbox.close;
$.colorbox.close = function () {
    if ($('#CustomerDetailsSaveBtn').hasClass('BackColorRed') || $('#CustomerPaymentsSaveBtn').hasClass('BackColorRed') || $('#CustomerPaymentGroupsSaveBtn').hasClass('BackColorRed') || $('#AddCustomerPaymentGroupsBtn').hasClass('BackColorRed') || $('#AddCustomerPaymentsBtn').hasClass('BackColorRed')) {
        jConfirm(Messages["ClosePopUp"], Messages["ClosePopUpTitle"], function (retVal) {
            if (retVal == true) {
                $("#AddCustomerDiv").empty();
                $("#tabCustomerGeneral").empty();
                $("#tabCustomerGroups").empty();
                $("#tabCustomerQuotations").empty();
                $("#tabCustomerInvoices").empty();
                $("#tabCustomerPayments").empty();
                $("#tabCustomerGeneral").removeClass("active in");
                $("#tabCustomerGroups").removeClass("active in");
                $("#tabCustomerQuotations").removeClass("active in");
                $("#tabCustomerInvoices").removeClass("active in");
                $("#tabCustomerPayments").removeClass("active in");
                $("#CustomerGeneral").removeClass("active");
                $("#CustomerGroups").removeClass("active");
                $("#CustomerQuotations").removeClass("active");
                $("#CustomerInvoices").removeClass("active");
                $("#CustomerPayments").removeClass("active");
                if (IsFromOperationRoom) {
                    LoadCustomerByID(LinkCustomerID, false);
                }
                else {
                    LoadCustomerGrid();
                }
                originalClose();
            }
        });
    }
    else {
        $("#AddCustomerDiv").empty();
        $("#tabCustomerGeneral").empty();
        $("#tabCustomerGroups").empty();
        $("#tabCustomerQuotations").empty();
        $("#tabCustomerInvoices").empty();
        $("#tabCustomerPayments").empty();
        $("#tabCustomerGeneral").removeClass("active in");
        $("#tabCustomerGroups").removeClass("active in");
        $("#tabCustomerQuotations").removeClass("active in");
        $("#tabCustomerInvoices").removeClass("active in");
        $("#tabCustomerPayments").removeClass("active in");
        $("#CustomerGeneral").removeClass("active");
        $("#CustomerGroups").removeClass("active");
        $("#CustomerQuotations").removeClass("active");
        $("#CustomerInvoices").removeClass("active");
        $("#CustomerPayments").removeClass("active");
        if (IsFromOperationRoom) {
            LoadCustomerByID(LinkCustomerID, false);
        }
        else {
            LoadCustomerGrid();
        }
        originalClose();
    }
};
$(document).on('change', '.ElementsForValidation', function () {
    if ($(this).valid()) {
        $(this).closest("form").find("#errorMessageClient").text("");
    }
    else
        $(this).closest("form").find("#errorMessageServer").hide();
    if (CustomerValidationClientSideHide) {
        if ($(this).closest("form").valid()) {
            $(this).closest("form").find("#errorMessageClient").text("");
        }
    }
    else if ($(this).valid()) {
        var elements = "#" + $(this).closest("form").attr("id") + " .error";
        $(elements).not('label').each(function () {
            $(this).valid();
        });
    }
});

